import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'
import { Observable } from 'rxjs'
import { Request } from 'express'
import { ObjectMapper, ObjectMapperStyle } from '@libs/lhy-common'

@Injectable()
export class RequestParameterSerializeInterceptor implements NestInterceptor {
  static readonly IGNORES = new WeakMap<Object, Array<string | symbol>>()

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    if (RequestParameterSerializeInterceptor.IGNORES.get(context.getClass())?.includes(context.getHandler().name)) {
      return next.handle()
    }

    const request = context.switchToHttp().getRequest<Request>()
    if (request?.query) {
      request.query = ObjectMapper.mapObject(request.query, ObjectMapperStyle.CamelCase)
    }
    if (request.body) {
      request.body = ObjectMapper.mapObject(request.body, ObjectMapperStyle.CamelCase)
    }
    if (request.params) {
      request.params = ObjectMapper.mapObject(request.params, ObjectMapperStyle.CamelCase)
    }

    return next.handle()
  }
}
